//
//  UIImage + Extensions.swift
//  SHWeibo2.0
//
//  Created by 黄礼潮 on 16/2/21.
//  Copyright © 2016年 黄礼潮. All rights reserved.
//

import UIKit

extension UIImage {
    
    class func cz_singleDotImage(color:UIColor) -> UIImage {
   
        //开启上下文、
        UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, UIScreen.mainScreen().scale)
        // 渲染
        color.setFill()
        UIRectFill(CGRect(x: 0, y: 0, width: 1, height: 1))
        //获取图片
        let result = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        //返回图像
        return result
    }
    
    
        func  cz_drawImage(size:CGSize,
        backColor:UIColor? = UIColor.whiteColor(),
        isCorner: Bool = false,
        finished:(image:UIImage)->()){
        
        //开启子线程绘图，因为没有更新UI,然后到主线程回调
        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            //设置了背景颜色，就不透明
            UIGraphicsBeginImageContextWithOptions(size, backColor != nil, UIScreen.mainScreen().scale)
            let rect = CGRect(origin:CGPointZero, size:size)
            //颜色填充
            backColor?.setFill()
            UIRectFill(rect)
            
            // 判断是否有圆角
            if isCorner {
            
                //先绘制路径，在绘制图形
                let path = UIBezierPath(ovalInRect: rect)
                //进行裁剪，后续的路径都会此路径被裁剪掉
                 path.addClip()
            }
            //绘制图像
            self.drawInRect(rect)
            //获得图像
            let result = UIGraphicsGetImageFromCurrentImageContext()
            
        
            //关闭上下文
            UIGraphicsEndImageContext()
            
            
            dispatch_async(dispatch_get_main_queue()) {
                
                finished(image: result)
                
            }
            
        }
        
    }

}
